<?php
/**
 * @fileName:CreateObject.php
 * @project: miaosang
 * @nameSpace:miaosang\yii2\traits
 * @Class CreateObject
 * @author : 吐火青蛙
 * @user : 吐火青蛙
 * @date : 2021-08-17 10:34
 * @desc : CreateObject
 * @Copyright (c)  2021,All Rights Reserved.
 */

namespace miaosang\yii2\traits;

trait CreateObject
{
    /**
     * @desc 创建yii2 组件
     * @param   $object
     * @return mixed
     * @throws \Exception
     */
    public function createObject($object)
    {
        $typeStr = strtolower(gettype($object));
        $component = null;
        switch ($typeStr) {
            case 'string':
                $object = trim($object);
                if ($object == null || $object == '' || $object == "") throw new \Exception($object . ' 不能为空!');
                // DB 是字符串，判断示例是否存在
                if (key_exists($object, \yii::$app->components)) {
                    $component = \yii::$app->{$object};
                } else {
                    throw new \Exception('组件【' . $object . '】配置有误!');
                }
                break;
            case 'object':
                $parentClass = get_parent_class($object);
                while ($parentClass != 'yii\base\Component' && $parentClass != '') {
                    $parentClass = get_parent_class($parentClass);
                }
                if ($parentClass != 'yii\base\Component') {
                    throw new \Exception('【' . get_class($object) . '】非yii2组件不可使用!');
                }
                $component = $object;
                break;
            case 'array':
                $class = isset($object['class']) ? $object['class'] : '';
                $parentClass = get_parent_class($class);
                while ($parentClass != 'yii\base\Component' && $parentClass != '') {
                    $parentClass = get_parent_class($parentClass);
                }
                if ($parentClass != 'yii\base\Component') {
                    throw new \Exception('【' . get_class($object) . '】非yii2组件不可使用!');
                }
                try {
                    $component = \yii::createObject($object);
                } catch (\Exception $ex) {
                    throw new \Exception('【' . $class . '】组件参数配置有误不可使用!');
                }
                break;
            default:
                throw new \Exception('不支持的yii2组件传入格式!仅支持传入yii2 组件的调用名称，组件配置,示例化的yii2组件');
                break;
        }
        return $component;
    }

}